const express = require('express')
const path = require('path')
const app = express()

app.use(express.urlencoded())
app.use(express.json())

app.use((req, res, next) => {
  const arr = ['http://127.0.0.1:5500', 'http://127.0.0.1:5501', 'http://127.0.0.1:5502']
  if (arr.includes(req.headers.origin)) {
    res.set('Access-Control-Allow-Origin',req.headers.origin)
    res.set('Access-Control-Allow-Headers','token')
  }
  next()
})

app.get('/user', (req, res) => {
  const { userId } = req.query

  if (userId !== '001') {
    return res.send({
      code: 10001,
      msg: '查询失败',
      data: null
    })
  }

  res.send({
    code: 10000,
    msg: '查询成功',
    data: {
      name: '程龙',
      age: 20,
      sex: '男'
    }
  })
})

app.post('/adduser', (req, res) => {
  const { name, age, sex } = req.body
  console.log(name, age, sex)
  if (!name || !age || !sex) {
    return res.send({
      code: 10001,
      msg: '查询失败',
      data: null
    })
  }

  res.send({
    code: 10000,
    msg: '查询成功',
    data: {
      name: '程龙',
      age: 20,
      sex: '女'
    }
  })
})

app.get('/userInfo', (req, res) => {
  const { userId } = req.query

  if (userId !== '001') {
    return res.send({
      code: 10001,
      msg: '查询失败',
      data: null
    })
  }

  res.send({
    code: 10000,
    msg: '查询成功',
    data: {
      name: '程龙',
      age: 20,
      sex: '男'
    }
  })
})

// jsonp跨域
app.get('/addInfo', (req, res) => {
  const { userId, cb } = req.query

  const data = {
    name: '刘中询',
    age: 22,
    sex: '男'
  }

  res.send(`${cb}(${JSON.stringify(data)})`)
})

// cors跨域
app.get('/info', (req, res) => {
  const { userId } = req.query

  if (userId !== '001') {
    return res.send({
      code: 10001,
      msg: '查询失败',
      data: null
    })
  }

  res.send({
    code: 10000,
    msg: '查询成功',
    data: {
      name: 'xiaoA',
      age: 20,
      sex: '男'
    }
  })
})

app.get('/1', (req, res) => {
  const filePath = path.resolve(__dirname, '3.get请求.html')
  res.sendFile(filePath)
})

app.get('/2', (req, res) => {
  const filePath = path.resolve(__dirname, '4.post请求.html')
  res.sendFile(filePath)
})

app.get('/3', (req, res) => {
  const filePath = path.resolve(__dirname, '5.拦截器练习.html')
  res.sendFile(filePath)
})

app.listen(8080, () => {
  console.log('成功');
})